package com.kfm.servlet;

import com.kfm.util.Constant;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.util.List;
import java.util.UUID;

@MultipartConfig(location = "d:/temp") // 上传文件必须加上这个注解
@WebServlet("/upload2")
public class UploadServlet2 extends HttpServlet {

    private final List<String> IMAGE_TYPES = List.of("image/jpeg", "image/png", "image/gif");


    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // 获取文件
        Part img = request.getPart("img");

        // 获取访问ip
        String remoteAddr = request.getRemoteAddr();
        System.out.println(remoteAddr + " 准备上传 " + img.getSubmittedFileName());

//        // 获取多个文件
//        Collection<Part> parts = request.getParts();
//        // 遍历集合
//        for (Part part : parts) {
//            System.out.println(part.getName());
//            System.out.println(part.getSubmittedFileName());
//            System.out.println(part.getSize());
//            System.out.println(part.getContentType());
//            System.out.println(part.getHeader("Content-Disposition"));
//        }


        // 获取文件类型
        String contentType = img.getContentType();
        System.out.println("getContentType : " + contentType);

        if (!IMAGE_TYPES.contains(contentType)){
            response.sendError(503, "上传的文件必须是图片(.jpeg/.png/.gif)");
            return;
        }

        // 获取文件大小
        long size = img.getSize();
        if (size > 1024 * 1024 * 10){
            response.sendError(503, "上传的文件不能超过10M");
            return;
        }

        // 按照日期存储. 获取日期的字符串 替换 - // 20231017
        String date = LocalDate.now().toString().replace("-", "");

        // 保存文件的路径   d:/temp/upload/20231017
        File file = new File(Constant.UPLOAD_PATH, date);

        // 判断文件夹是否存在
        if (!file.exists()){
            // 不存在创建
            file.mkdirs();
        }

        /*
         重命名文件，防止文件冲突
            时间戳
            UUID
         */
        String submittedFileName = img.getSubmittedFileName(); // cat.jpg

        // 获取文件名后缀
//        int i = submittedFileName.lastIndexOf(".");
//        String suffix = submittedFileName.substring(i); // .jpg

        String substring = submittedFileName.substring(submittedFileName.lastIndexOf("."));// .jpg


        String fileName = UUID.randomUUID().toString().replace("-", "");
        // 存文件  d:/temp/upload/20231017/fileName + substring
        img.write(file.getAbsolutePath() + File.separator + fileName + substring);



        // 给返回一个访问 /下载的链接
        response.setContentType("text/html;charset=utf-8");

        PrintWriter writer = response.getWriter();
        // 访问链接
        writer.println("<h1>文件上传成功！</h1>");

        String param = date + File.separator + fileName + substring;

        System.out.println(remoteAddr + " 上传文件成功：" + param);
        // url 编码
        String encode = URLEncoder.encode(param, "utf-8");
        writer.println("<a href='download?file=%s'>访问链接</a>".formatted(encode));
        writer.println("<a href='download?file=%s&download=true'>下载链接</a>".formatted(encode));

    }
}
